# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     image_compress                  |
|Author:        WYT                      |
|date:          2020/6/9                  |
 ----------------------------------------
|  Change Activity:                      |
|                   2020/6/9:             | 
-----------------------------------------
"""
import os

from PIL import Image, ImageFile

img_path = r"C:\Users\Administrator\Desktop\Project\autoflow\materials\GR_2020\ctp\GR_307566\buslic.png"


def compress_image(outfile, mb=190, quality=85, k=0.9):
    """不改变图片尺寸压缩到指定大小
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标，KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址，压缩文件大小
    """

    o_size = os.path.getsize(outfile) // 1024
    print(o_size, mb)
    if o_size <= mb:
        return outfile

    ImageFile.LOAD_TRUNCATED_IMAGES = True
    while o_size > mb:
        im = Image.open(outfile)
        x, y = im.size
        out = im.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
        try:
            out.save(outfile, quality=quality)
        except Exception as e:
            print(e)
            break
        o_size = os.path.getsize(outfile) // 1024
    return outfile

if __name__ == '__main__':
    out = compress_image(outfile=img_path, mb=80, quality=75, k=0.9)
    print(out)
